#include <modbus/modbus.h>
#include <modbus/test_main.h>
#include "hilog/log.h"

modbus_t *ctx;
uint16_t *tab_rp_registers;

int modbusInitConnect(void){
    ctx = modbus_new_tcp("192.168.137.1", 502);
    modbus_set_debug(ctx, TRUE);
    if (modbus_connect(ctx) == -1) {
        OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Modbus", "[Modbus CONNECT]Connected ERROR");
        modbus_free(ctx);
        return -1;
    }
    
    //判断modbus连接是否成功
    if (modbus_connect(ctx) == -1) {
        OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Modbus", "[Modbus CONNECT]Connection failed");
        modbus_free(ctx);
        return -1;
    }
    
    int rc = modbus_set_slave(ctx, 0x01);   
    if (rc == -1) {
        OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Modbus", "[Modbus CONNECT]Invalid slave ID");
        modbus_free(ctx);
        return -1;
    }    
    
    
    modbus_set_response_timeout(ctx,666,0);
    
    OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Modbus", "[Modbus CONNECT]Connected OK");
    
    return 1;
}

float modbus_main(void){
    
//    int regs = modbus_read_input_registers(ctx, 0, 1, tab_reg); //读取传感器数值
    
    tab_rp_registers = (uint16_t *) malloc(2 * sizeof(uint16_t));
    memset(tab_rp_registers, 0, 2 * sizeof(uint16_t));
    
    int regs = modbus_read_registers(ctx, 0, 2, tab_rp_registers);
    
    float aa = modbus_get_float_abcd(tab_rp_registers);
    
    OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Modbus", "[Modbus]%{public}d",regs);
    OH_LOG_Print(LOG_APP, LOG_INFO, 0xFF00, "Modbus", "[Modbus]%{public}f",aa);
    
//        rc = modbus_read_input_registers(ctx,0,1, tab_reg);
////        if (rc == -1) {
////        fprintf(stderr, "%s error-test\n", modbus_strerror(errno));
////        return -1;
    

    
    return aa;
}

